package com.example.rocketmq.demo.producer;

import com.example.rocketmq.demo.config.RocketMQConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * 延时消息生产者
 */
@Slf4j
@Component
public class DelayProducer {

    @Autowired
    @Qualifier("defaultMQProducer")
    private DefaultMQProducer producer;

    /**
     * 发送延时消息
     *
     * @param content 消息内容
     * @param delayLevel 延时等级 (1s/5s/10s/30s/1m/2m/3m/4m/5m/6m/7m/8m/9m/10m/20m/30m/1h/2h)
     *                  对应的值为：1到18
     * @return 发送结果
     */
    public SendResult sendDelay(String content, int delayLevel) throws Exception {
        Message message = new Message(
                RocketMQConstant.TOPIC_DELAY,
                RocketMQConstant.TAG_DELAY,
                content.getBytes(StandardCharsets.UTF_8)
        );

        // 设置延时等级
        message.setDelayTimeLevel(delayLevel);

        SendResult sendResult = producer.send(message);
        log.info("延时消息发送结果: {}, 延时等级: {}", sendResult, delayLevel);
        return sendResult;
    }
}
